#!/bin/bash

# npm 发布脚本
echo "🚀 开始 npm 发布流程..."

# 检查是否登录 npm
if ! npm whoami; then
    echo "❌ 请先登录 npm: npm login"
    exit 1
fi

# 检查是否有未提交的更改
if [[ -n $(git status --porcelain) ]]; then
    echo "❌ 有未提交的更改，请先提交或暂存"
    git status --porcelain
    exit 1
fi

# 运行测试
echo "🧪 运行测试..."
npm test

if [ $? -ne 0 ]; then
    echo "❌ 测试失败，发布中止"
    exit 1
fi

# 检查版本号
echo "📋 当前版本: $(node -p "require('./package.json').version")"

# 询问是否继续
read -p "是否继续发布？(y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "❌ 发布已取消"
    exit 1
fi

# 发布到 npm
echo "📦 发布到 npm..."
npm publish

if [ $? -eq 0 ]; then
    echo "✅ 发布成功！"
    
    # 创建 git tag
    VERSION=$(node -p "require('./package.json').version")
    git tag "v$VERSION"
    git push origin "v$VERSION"
    
    echo "📤 推送标签到 Gitee: v$VERSION"
    
    echo "🏷️ 已创建并推送标签 v$VERSION"
else
    echo "❌ 发布失败"
    exit 1
fi
